﻿using System;
using System.IO;

namespace QQ2564874169.File
{
    public class LocalWinFile : IFile
    {
        private string _dir;
        private string _domain;

        public LocalWinFile(string dir, string domain = null)
        {
            if (string.IsNullOrWhiteSpace(dir))
                throw new ArgumentNullException(nameof(dir));

            _dir = dir;
            _domain = domain ?? "";
        }

        private string SetPath(string path)
        {
            if (!path.StartsWith("/"))
            {
                path = "/" + path;
            }
            if (path.Contains("/"))
            {
                path = path.Replace("/", Path.DirectorySeparatorChar.ToString());
            }
            return _dir + path;
        }

        public void Create(string path, Stream file)
        {
            path = SetPath(path);

            var dir = Path.GetDirectoryName(path);

            if (dir != null && Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }

            var data = new byte[4096];
            using (var sm = new FileStream(path, FileMode.Create))
            {
                file.Position = 0;
                int count;
                while ((count = file.Read(data, 0, data.Length)) > 0)
                {
                    sm.Write(data, 0, count);
                }
            }
        }

        public bool ExistsFile(string path)
        {
            path = SetPath(path);
            return System.IO.File.Exists(path);
        }

        public void RemoveFile(string path)
        {
            path = SetPath(path);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
        }

        public string GetUri(string path)
        {
            if (path == null)
                return null;

            if (_domain.Length < 1)
            {
                return SetPath(path);
            }
            path = path.Replace("\\", "/");

            if (path.StartsWith("/") == false)
            {
                path = "/" + path;
            }
            return _domain + path;
        }

        public Stream GetFile(string path)
        {
            if (path == null)
                return null;
            path = SetPath(path);
            return System.IO.File.Open(path, FileMode.Open);
        }
    }
}
